from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from typing import Optional
from app.database import get_db
from app import models, schemas
from app.routers.admin_auth import verify_admin_token

router = APIRouter(prefix="/admin", tags=["管理后台"])


# 模型管理
@router.post("/models", response_model=schemas.Response)
async def create_model(
    request: schemas.ModelCreate,
    db: Session = Depends(get_db),
    admin: models.Admin = Depends(verify_admin_token)
):
    """创建模型"""
    model = models.Model(**request.dict())
    db.add(model)
    db.commit()
    db.refresh(model)
    return schemas.Response(message="创建成功", data=schemas.ModelResponse.from_orm(model))


@router.get("/models", response_model=schemas.Response)
async def list_models(
    page: int = Query(1, ge=1),
    page_size: int = Query(20, ge=1, le=100),
    db: Session = Depends(get_db),
    admin: models.Admin = Depends(verify_admin_token)
):
    """获取模型列表"""
    query = db.query(models.Model)
    total = query.count()
    models_list = query.offset((page - 1) * page_size).limit(page_size).all()
    
    return schemas.Response(data={
        "items": [schemas.ModelResponse.from_orm(m) for m in models_list],
        "total": total,
        "page": page,
        "page_size": page_size
    })


@router.patch("/models/{model_id}", response_model=schemas.Response)
async def update_model(
    model_id: int,
    request: schemas.ModelUpdate,
    db: Session = Depends(get_db),
    admin: models.Admin = Depends(verify_admin_token)
):
    """更新模型"""
    model = db.query(models.Model).filter(models.Model.id == model_id).first()
    if not model:
        raise HTTPException(status_code=404, detail="模型不存在")
    
    update_data = request.dict(exclude_unset=True)
    for field, value in update_data.items():
        setattr(model, field, value)
    
    db.commit()
    db.refresh(model)
    return schemas.Response(message="更新成功", data=schemas.ModelResponse.from_orm(model))


# Agent管理
@router.post("/agents", response_model=schemas.Response)
async def create_agent(
    request: schemas.AgentCreate,
    db: Session = Depends(get_db),
    admin: models.Admin = Depends(verify_admin_token)
):
    """创建Agent"""
    # 验证 category_id 是否存在
    if request.category_id:
        category = db.query(models.Category).filter(models.Category.id == request.category_id).first()
        if not category:
            raise HTTPException(status_code=400, detail="分类不存在")
    else:
        raise HTTPException(status_code=400, detail="必须选择一个分类")
    
    agent_data = request.dict(exclude={"tool_ids"})
    agent = models.Agent(**agent_data)
    
    # 添加工具关联
    if request.tool_ids:
        tools = db.query(models.Tool).filter(models.Tool.id.in_(request.tool_ids)).all()
        agent.tools = tools
    
    db.add(agent)
    db.commit()
    db.refresh(agent)
    return schemas.Response(message="创建成功", data=schemas.AgentResponse.from_orm(agent))


@router.get("/agents", response_model=schemas.Response)
async def list_all_agents(
    page: int = Query(1, ge=1),
    page_size: int = Query(15, ge=1, le=100),
    db: Session = Depends(get_db),
    admin: models.Admin = Depends(verify_admin_token)
):
    """获取所有启用的Agent列表"""
    query = db.query(models.Agent).filter(models.Agent.enabled == True)
    total = query.count()
    agents = query.offset((page - 1) * page_size).limit(page_size).all()
    
    return schemas.Response(data={
        "items": [schemas.AgentResponse.from_orm(a) for a in agents],
        "total": total,
        "page": page,
        "page_size": page_size
    })


@router.patch("/agents/{agent_id}", response_model=schemas.Response)
async def update_agent(
    agent_id: int,
    request: schemas.AgentUpdate,
    db: Session = Depends(get_db),
    admin: models.Admin = Depends(verify_admin_token)
):
    """更新Agent"""
    agent = db.query(models.Agent).filter(models.Agent.id == agent_id).first()
    if not agent:
        raise HTTPException(status_code=404, detail="Agent不存在")
    
    # 验证 category_id 是否存在
    if request.category_id is not None:
        if request.category_id:
            category = db.query(models.Category).filter(models.Category.id == request.category_id).first()
            if not category:
                raise HTTPException(status_code=400, detail="分类不存在")
        else:
            raise HTTPException(status_code=400, detail="必须选择一个分类")
    
    update_data = request.dict(exclude_unset=True, exclude={"tool_ids"})
    for field, value in update_data.items():
        setattr(agent, field, value)
    
    # 更新工具关联
    if request.tool_ids is not None:
        tools = db.query(models.Tool).filter(models.Tool.id.in_(request.tool_ids)).all()
        agent.tools = tools
    
    db.commit()
    db.refresh(agent)
    return schemas.Response(message="更新成功", data=schemas.AgentResponse.from_orm(agent))


@router.delete("/agents/{agent_id}", response_model=schemas.Response)
async def delete_agent(
    agent_id: int,
    db: Session = Depends(get_db),
    admin: models.Admin = Depends(verify_admin_token)
):
    """删除Agent（软删除，设置enabled=0）"""
    agent = db.query(models.Agent).filter(models.Agent.id == agent_id).first()
    if not agent:
        raise HTTPException(status_code=404, detail="Agent不存在")
    
    # 软删除：设置 enabled = 0
    agent.enabled = False
    db.commit()
    
    return schemas.Response(message="删除成功")


# 工具管理
@router.post("/tools", response_model=schemas.Response)
async def create_tool(
    request: schemas.ToolCreate,
    db: Session = Depends(get_db),
    admin: models.Admin = Depends(verify_admin_token)
):
    """创建工具"""
    tool = models.Tool(**request.dict())
    db.add(tool)
    db.commit()
    db.refresh(tool)
    return schemas.Response(message="创建成功", data=schemas.ToolResponse.from_orm(tool))


@router.get("/tools", response_model=schemas.Response)
async def list_tools(
    page: int = Query(1, ge=1),
    page_size: int = Query(20, ge=1, le=100),
    db: Session = Depends(get_db),
    admin: models.Admin = Depends(verify_admin_token)
):
    """获取工具列表"""
    query = db.query(models.Tool)
    total = query.count()
    tools = query.offset((page - 1) * page_size).limit(page_size).all()
    
    return schemas.Response(data={
        "items": [schemas.ToolResponse.from_orm(t) for t in tools],
        "total": total,
        "page": page,
        "page_size": page_size
    })


@router.patch("/tools/{tool_id}", response_model=schemas.Response)
async def update_tool(
    tool_id: int,
    request: schemas.ToolUpdate,
    db: Session = Depends(get_db),
    admin: models.Admin = Depends(verify_admin_token)
):
    """更新工具"""
    tool = db.query(models.Tool).filter(models.Tool.id == tool_id).first()
    if not tool:
        raise HTTPException(status_code=404, detail="工具不存在")
    
    update_data = request.dict(exclude_unset=True)
    for field, value in update_data.items():
        setattr(tool, field, value)
    
    db.commit()
    db.refresh(tool)
    return schemas.Response(message="更新成功", data=schemas.ToolResponse.from_orm(tool))


# 用户管理
@router.get("/users", response_model=schemas.Response)
async def list_users(
    page: int = Query(1, ge=1),
    page_size: int = Query(20, ge=1, le=100),
    db: Session = Depends(get_db),
    admin: models.Admin = Depends(verify_admin_token)
):
    """获取用户列表"""
    query = db.query(models.User)
    total = query.count()
    users = query.offset((page - 1) * page_size).limit(page_size).all()
    
    return schemas.Response(data={
        "items": [schemas.UserResponse.from_orm(u) for u in users],
        "total": total,
        "page": page,
        "page_size": page_size
    })


# 热门工具配置
@router.post("/hot-tools", response_model=schemas.Response)
async def add_hot_tool(
    agent_id: int,
    sort: int = 0,
    db: Session = Depends(get_db),
    admin: models.Admin = Depends(verify_admin_token)
):
    """添加热门工具"""
    hot_tool = models.HotTool(agent_id=agent_id, sort=sort)
    db.add(hot_tool)
    db.commit()
    return schemas.Response(message="添加成功")


@router.delete("/hot-tools/{hot_tool_id}", response_model=schemas.Response)
async def remove_hot_tool(
    hot_tool_id: int,
    db: Session = Depends(get_db),
    admin: models.Admin = Depends(verify_admin_token)
):
    """删除热门工具"""
    hot_tool = db.query(models.HotTool).filter(models.HotTool.id == hot_tool_id).first()
    if hot_tool:
        db.delete(hot_tool)
        db.commit()
    return schemas.Response(message="删除成功")

